package com.example.simple

import android.os.Bundle
import android.util.Log
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.tooling.preview.Preview
import com.android.billingclient.api.BillingClient
import com.android.billingclient.api.BillingClient.BillingResponseCode
import com.android.billingclient.api.Purchase
import com.example.gpay.GPay
import com.example.gpay.GPayHandle
import com.example.simple.ui.theme.SimpleTheme
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        GPay.init(application, object : GPayHandle {
            override suspend fun onVerifyPurchase(purchase: Purchase): Boolean {
                return true
            }

            override fun onConsumeSuccess(purchase: Purchase) {
                purchase.logDebug()
                Toast.makeText(this@MainActivity, "onConsumeSuccess", Toast.LENGTH_LONG).show()
            }

            override fun onAcknowledgePurchaseSuccess(purchase: Purchase) {
                purchase.logDebug()
                Toast.makeText(this@MainActivity, "onAcknowledgePurchaseSuccess", Toast.LENGTH_LONG).show()
            }

            override fun logReviewOrder(log: String) {
                log.logDebug()
            }

            override fun logReviewOrderResp(log: String) {
                log.logDebug()

            }

            override fun logLaunchPay(log: String) {
                log.logDebug()
            }

            override fun logLaunchPayResp(log: String) {
                log.logDebug()

            }

            override fun logVerifyOrder(log: String) {
                log.logDebug()

            }

            override fun logVerifyOrderResp(log: String) {
                log.logDebug()

            }

            override fun logConsumeOrder(log: String) {
                log.logDebug()

            }

            override fun logConsumeOrderResp(log: String) {
                log.logDebug()

            }

            override fun logAcknowledgedOrder(log: String) {
                log.logDebug()

            }

            override fun logAcknowledgedOrderResp(log: String) {
                log.logDebug()

            }

            override fun logRestoreVerifyOrder(log: String) {
                log.logDebug()

            }

            override fun logRestoreVerifyOrderResp(log: String) {
                log.logDebug()

            }

            override fun logRestoreConsumeOrder(log: String) {
                log.logDebug()

            }

            override fun logRestoreConsumeOrderResp(log: String) {
                log.logDebug()

            }

            override fun logRestoreAcknowledgedOrder(log: String) {
                log.logDebug()

            }

            override fun logRestoreAcknowledgedOrderResp(log: String) {
                log.logDebug()

            }
        })
        enableEdgeToEdge()
        setContent {
            SimpleTheme {
                Scaffold(modifier = Modifier.fillMaxSize()) { innerPadding ->
                    Box(
                        modifier = Modifier
                            .fillMaxSize()
                            .padding(innerPadding)
                    ) {

                        val showLoading = remember { mutableStateOf(false) }

                        if (showLoading.value) {
                            AlertDialog(onDismissRequest = {}, confirmButton = {}, text = { Text("loading...") })
                        }

                        Column(modifier = Modifier.align(Alignment.Center)) {
                            Button(onClick = {

                                showLoading.value = true
                                GlobalScope.launch(Dispatchers.IO) {
                                    val result = GPay.purchase(
                                        this@MainActivity,
                                        orderNo = "orderno_product_id_1",
                                        "product_id_1",
                                        BillingClient.ProductType.INAPP
                                    )
                                    GlobalScope.launch(Dispatchers.Main) {
                                        showLoading.value = false
                                        if (result.response == BillingResponseCode.OK) {
                                            Toast.makeText(this@MainActivity, "ok", Toast.LENGTH_LONG).show()
                                        } else if (result.response == BillingResponseCode.USER_CANCELED) {
                                            Toast.makeText(this@MainActivity, "cancel", Toast.LENGTH_LONG).show()
                                        } else {
                                            Toast.makeText(this@MainActivity, "error: ${result.message}", Toast.LENGTH_LONG).show()
                                        }

                                    }
                                }
                            }, modifier = Modifier) {
                                Text("inapp 1")
                            }
                            Button(onClick = {

                                showLoading.value = true
                                GlobalScope.launch(Dispatchers.IO) {
                                    val result = GPay.purchase(
                                        this@MainActivity,
                                        orderNo = "orderno_product_id_2",
                                        "product_id_2",
                                        BillingClient.ProductType.INAPP
                                    )
                                    GlobalScope.launch(Dispatchers.Main) {
                                        showLoading.value = false
                                        if (result.response == BillingResponseCode.OK) {
                                            Toast.makeText(this@MainActivity, "ok", Toast.LENGTH_LONG).show()
                                        } else if (result.response == BillingResponseCode.USER_CANCELED) {
                                            Toast.makeText(this@MainActivity, "cancel", Toast.LENGTH_LONG).show()
                                        } else {
                                            Toast.makeText(this@MainActivity, "error: ${result.message}", Toast.LENGTH_LONG).show()
                                        }

                                    }
                                }
                            }, modifier = Modifier) {
                                Text("inapp 2")
                            }
                            Button(onClick = {

                                showLoading.value = true
                                GlobalScope.launch(Dispatchers.IO) {
                                    val result = GPay.purchase(
                                        this@MainActivity,
                                        orderNo = "orderno_product_id_3",
                                        "product_id_3",
                                        BillingClient.ProductType.INAPP
                                    )
                                    GlobalScope.launch(Dispatchers.Main) {
                                        showLoading.value = false
                                        if (result.response == BillingResponseCode.OK) {
                                            Toast.makeText(this@MainActivity, "ok", Toast.LENGTH_LONG).show()
                                        } else if (result.response == BillingResponseCode.USER_CANCELED) {
                                            Toast.makeText(this@MainActivity, "cancel", Toast.LENGTH_LONG).show()
                                        } else {
                                            Toast.makeText(this@MainActivity, "error: ${result.message}", Toast.LENGTH_LONG).show()
                                        }

                                    }
                                }
                            }, modifier = Modifier) {
                                Text("inapp 3")
                            }
                            Button(onClick = {

                                showLoading.value = true
                                GlobalScope.launch(Dispatchers.IO) {
                                    val result = GPay.purchase(
                                        this@MainActivity,
                                        orderNo = "orderno_product_subs_1",
                                        "product_subs_1",
                                        BillingClient.ProductType.SUBS
                                    )
                                    GlobalScope.launch(Dispatchers.Main) {
                                        showLoading.value = false
                                        if (result.response == BillingResponseCode.OK) {
                                            Toast.makeText(this@MainActivity, "ok", Toast.LENGTH_LONG).show()
                                        } else if (result.response == BillingResponseCode.USER_CANCELED) {
                                            Toast.makeText(this@MainActivity, "cancel", Toast.LENGTH_LONG).show()
                                        } else {
                                            Toast.makeText(this@MainActivity, "error: ${result.message}", Toast.LENGTH_LONG).show()
                                        }

                                    }
                                }
                            }, modifier = Modifier) {
                                Text("subs 1")
                            }
                            Button(onClick = {
                                GPay.restore()
                            }, modifier = Modifier) {
                                Text("restore")
                            }
                        }

                    }
                }
            }
        }
    }
}

@Composable
fun Greeting(name: String, modifier: Modifier = Modifier) {
    Text(
        text = "Hello $name!",
        modifier = modifier
    )
}

@Preview(showBackground = true)
@Composable
fun GreetingPreview() {
    SimpleTheme {
        Greeting("Android")
    }
}

fun Any?.logDebug() {
    Log.d("google_pay", this?.toString() ?: "null")
}